package com.varian.system.listener;

import com.rabbitmq.client.Channel;
import com.varian.log.constant.LogConstant;
import com.varian.log.model.ApiLogger;
import com.varian.redis.util.RedisUtil;
import com.varian.system.constant.SystemConstant;
import com.varian.system.service.IApiLogService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author ben
 * @since 2024/7/23
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ApiLogListener {

    private final IApiLogService apiLogService;

    @SneakyThrows
    @RabbitListener(queues = LogConstant.QUEUE_API_LOG)
    public void onApiMessage(ApiLogger message, MessageProperties properties, Channel channel) {
        try {
            RedisUtil.lock(SystemConstant.KEY_API_LOG.format(message.getTraceId()), () -> {
                apiLogService.saveApiLog(message);
            });
        } catch (Exception e) {
            log.error("保存API日志失败", e);
            channel.basicReject(properties.getDeliveryTag(), true);
        }
    }

    @SneakyThrows
    @RabbitListener(queues = LogConstant.QUEUE_API_ERROR_LOG)
    public void onApiErrorMessage(ApiLogger message, MessageProperties properties, Channel channel) {
        try {
            RedisUtil.lock(SystemConstant.KEY_API_ERROR_LOG.format(message.getTraceId()), () -> {
                apiLogService.saveApiErrorLog(message);
            });
        } catch (Exception e) {
            log.error("保存API错误日志失败", e);
            channel.basicReject(properties.getDeliveryTag(), true);
        }
    }
}
